package com.pucheng.bracelet.app.weight

import android.content.Context
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import com.blankj.utilcode.util.ScreenUtils
import com.pucheng.bracelet.R
import com.zyyoona7.popup.EasyPopup
import com.zyyoona7.popup.XGravity
import com.zyyoona7.popup.YGravity
import me.hgj.jetpackmvvm.demo.app.ext.setOnViewClick

/**
@author JesseLee
@date : 2021/2/23 15:33
 */
 class UnitPopup(
    private val context: Context,
    private var is12Unit: Boolean= false,
    private var  unitName: String = "",
    private val callback: (is12Unit: Boolean, unitName: String) -> Unit
) {
    private lateinit var iv12Unit: ImageView
    private lateinit var iv24Unit: ImageView
    private lateinit var tv12Unit: TextView
    private lateinit var tv24Unit: TextView

    private val easyPopup by lazy {
        EasyPopup.create()
            .setContentView(context, R.layout.time_unit_popup)
            .setWidth(ScreenUtils.getScreenWidth() * 3 / 4)
            .setBackgroundDimEnable(true)
            .setFocusAndOutsideEnable(true)
            .apply()
            .setOnViewClick(R.id.cl_12_unit) { _: View, _: EasyPopup ->
                setImage(iv12Unit, iv24Unit, tv12Unit.text as String, true)
            }
            .setOnViewClick(R.id.cl_24_unit) { _: View, _: EasyPopup ->
                setImage(iv12Unit, iv24Unit, tv24Unit.text as String, false)
            }
            .setOnViewClick(R.id.tv_unit_ok) { _: View, easyPopup: EasyPopup ->
                callback.invoke(is12Unit, unitName)
                easyPopup.dismiss()
            }
    }

    fun show(view: View) {
        easyPopup.apply {
            iv12Unit = easyPopup.findViewById<ImageView>(R.id.iv_12_unit)
            tv12Unit = easyPopup.findViewById<TextView>(R.id.tv_12_unit)
            iv24Unit = easyPopup.findViewById<ImageView>(R.id.iv_24_unit)
            tv24Unit = easyPopup.findViewById<TextView>(R.id.tv_24_unit)
            setImage(iv12Unit, iv24Unit, unitName, is12Unit)
            showAtAnchorView(view,YGravity.CENTER,XGravity.CENTER)
        }
    }

    private fun setImage(
        iv12Unit: ImageView? = null,
        iv24Unit: ImageView? = null,
        name: String,
        isSelect12: Boolean
    ) {
        if (iv12Unit != null && iv24Unit != null) {
            is12Unit = isSelect12
            unitName = name
            if (isSelect12) {
                iv12Unit.setImageResource(R.mipmap.blue_slec)
                iv24Unit.setImageResource(R.mipmap.gray_slec)
            } else {
                iv24Unit.setImageResource(R.mipmap.blue_slec)
                iv12Unit.setImageResource(R.mipmap.gray_slec)
            }
        }
    }

}
